package com.example.demo.controller;

import com.example.demo.model.service.MarkService;
import com.example.demo.model.service.UserService;
import com.example.demo.model.valueObject.UserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class UserRegist {
    private final static String userRegistUrl = "/regist";
    private final static String loginPage = "index";
    @Autowired
    private UserService userService;
    @Autowired
    private MarkService markService;
    @PostMapping(userRegistUrl)
    public String regist(@RequestParam("id")String id,
                         @RequestParam("name") String name,
                         @RequestParam("password")String password,
                         HttpServletRequest request)
    {
        String message = "";
        if(id.trim().equals("")||name.trim().equals("")||password.trim().equals(""))
        {
            message = "任意字段不能为空";
            request.setAttribute("message",message);
            return loginPage;
        }
        UserLogin userLogin = new UserLogin();
        userLogin.setId(id.trim());
        userLogin.setName(name.trim());
        userLogin.setPassword(password.trim());
        if(ifUserExist(userLogin))
        {
            message = "用户id已存在";
        }else
        {
            userService.userRegist(userLogin);
            markService.InsertNewUsers(id.trim());
            message = "注册成功";
        }
        request.setAttribute("message",message);
        return loginPage;
    }
    //判断用户是否存在
    protected boolean ifUserExist(UserLogin userLogin)
    {
        UserLogin tmp = userService.getUserById(userLogin.getId());
        if(tmp==null||tmp.getId()==null||tmp.getName()==null)
        {
            return false;
        }
        return true;
    }
}
